<template>
	<basic-container>
		<avue-crud :option="option" :data="data" ref="crud" v-model="form" :table-loading="loading" :permission="permissionList"
		@search-change="searchChange" :page.sync="page" @refresh-change="refreshChange" @search-reset="searchReset"
		@current-change="currentChange" @size-change="sizeChange" >
			<!-- 搜索自定义 -->
			<template slot="search">
			    <div style="padding: 0 10px;float: left;width: 25%;">
                    <el-form-item label="商品分类">
                        <el-cascader v-model="productData" :options="chooseProductOption" size="mini" @change="handleChange"></el-cascader>
                    </el-form-item>
                </div>
			</template>
			<template slot-scope="scope" slot="menu">
				<el-button icon="el-icon-view"  type="text" size="small" @click="lookOver(scope.row.id)">查看</el-button>
				<el-button v-if="goodsStatus != 0 " type="text" icon="el-icon-edit" @click="viewGoodsDetail(scope.row.id)" size="small">编辑</el-button>
				<el-button v-if="goodsStatus == 0 " type="text" icon="el-icon-edit" @click="editalStock(scope.row.id)" size="small">编辑库存</el-button>
				<el-button v-if="goodsStatus == 1 " @click="upperOrlower(scope.row.id,0)" type="text" size="small">上架</el-button>
				<el-button v-if="goodsStatus == 0 " @click="upperOrlower(scope.row.id,1)" type="text" size="small">下架</el-button>
			</template>
			<template slot-scope="{row}" slot="goodsMainPhotoUrl">
				<img :src="row.goodsMainPhotoUrl" style="width:50px;height:50px;" />
			</template>
			<!--<template slot-scope="{row}" slot="storeRecommend">
				<el-switch @change="rowSwitchChange(row)" v-model="row.storeRecommend"></el-switch>
			</template>-->
		</avue-crud>
		<el-drawer title="商品详情" size="80%" :withHeader=false :visible.sync="dialogTableVisible" width="80%">
			<add-goods v-if="dialogTableVisible" :disadledSpec="disadledSpec" :goodsId="goodsId" :isPublish="isPublish" :isCheck="isCheck" :isRedact="isRedact"></add-goods>
		</el-drawer>
		<el-drawer title="库存列表" size="60%" :visible.sync="stockVisible" :destroy-on-close='true' @close="closeDrawer" >
			<div style="padding: 20px;">
				<avue-crud :option="optionStock" :data="stockData" ref="stockCrud" v-model="stockForm" :table-loading="stockLoading"
						   :permission="permissionList" @refresh-change="refreshStockChange">
					<template slot-scope="scope" slot="menu">
						<el-button @click="editStock(scope.row)" type="text" size="small">编辑库存</el-button>
					</template>
				</avue-crud>
			</div>
		</el-drawer>
		<el-dialog title="库存详情" :visible.sync="stockView" width="40%">
			<avue-form ref="stockRef" v-model="stockDetail" :option="stockDetailOption">
				<template slot="skuName">
					<el-tag color="#fff"
							style="border: none;color: #333333;white-space: pre-wrap;line-height: 24px;;padding-top: 6px;height: auto;">{{stockDetail.skuName}}</el-tag>
				</template>
				<template slot="stocks">
					<el-tag color="#fff"
							style="border: none;color: #333333;">{{stockDetail.stocks}}</el-tag>
				</template>
				<template slot="menuForm">
					<el-button type="primary" @click="handleSubmit">提 交</el-button>
					<el-button @click="handleEmpty">取消</el-button>
				</template>
			</avue-form>
		</el-dialog>
	</basic-container>
</template>

<script>
	import {
		getList,
		getGoodsClassAll,
		updateDisplay,
		upperOrlower,
		showGoodsStock,
		editGoodsStock
	} from "@/api/base/goods/seller/integralGoods";
	import {
		mapGetters
	} from "vuex";
	import addGoods from '@/views/base/integral/seller/addIntegralGoods';
	export default {
		props: ["goodsStatus"],
		data() {
			return {
				isPublish: false,
				isCheck: false,
				isRedact: false,
				disadledSpec:false,
				goodsId: "",
				dialogTableVisible: false,
				refuseResion: "",
				searchForm: {},
				chooseProductOption: [],
				productData: [],
				form: {
					goodsPrice: ""
				},
				query: {},
				addForm: {
					goodsInventory: ""
				},
				multipleSelection: [],
				addDialog: false,
				loading: true,
				rolesTree: [],
				classData: [],
				cascaderProps: {
					id: "id",
					label: "className",
					children: "childrenNodes"
				},
				classList: [],
				rolesKeys: [],
				box: false,
				data: [],
				ParentGoods: [],
				// 选中的父级分类id数组
				selectedKeys: [],
				page: {
					pageSize: 10,
					currentPage: 1,
					total: 0
				},
				option: {
					size: "mini",
					excelBtn: false,
					tip: false,
					//menu: false,
					addBtn: true,
					border: true,
					index: false,
					selection: false,
					editBtn: false,
					viewBtn: false,
					delBtn: false,
					searchBtn: false,
					refreshBtn: false,
					columnBtn: false,
					rowKey: "id",
					// calcHeight: 380,80,
					dialogType: "dialog",
					menuWidth: 160,
					align: "center",
					column: [
						{
							label: "商品名称",
							prop: "goodsName",
							fixed: true,
							search: true,
							width:240,
							rules: [{
								required: true,
								message: "请输入商品名称",
								trigger: "blur"
							}]
						},{
							label: "商品图片",
							prop: "goodsMainPhotoUrl",
							slot: true,
							rules: [{
								required: true,
								message: "请输入主图片",
								trigger: "blur"
							}]
						},

						{
							label: "商品分类",
							prop: "goodsClassId",
							dicUrl: "base/sellerGoodsClass/listDicData",
							props: {
								label: "label",
								value: "value"
							},
							rules: [{
								required: true,
								message: "请输入分类",
								trigger: "blur"
							}]
						},
						{
							label: "库存量",
							prop: "stock",
							width:150,
							rules: [{
								required: true,
								message: "请输入商品价格",
								trigger: "blur"
							}]
						},
						{
							label: "积分数",
							prop: "showPrice",
							formatter:function(row,value,label,column){
								return value.split(".")[0];
							},
							rules: [{
								required: true,
								message: "积分数",
								trigger: "blur"
							}]
						},
						//卖家商品列表页面展示的“推荐”是店铺是否推荐，编辑页面的单选按钮“商品推荐”，也是店铺是否推荐 storeRecommend
						// {
						// 	label: "推荐",
						// 	prop: "storeRecommend",
						// 	slot: true,
						// },
						{
							label: "权重",
							prop: "goodsSort",
						}
					]
				},
				//编辑库存的一些参数
				stockVisible: false,
				stockLoading: false,
				stockForm: {},
				stockData: [],
				goodId: '',
				stockView: false,
				stock: '',
				goodsStockFlag: true,
				optionStock: {
					size: "mini",
					excelBtn: false,
					tip: false,
					addBtn: true,
					border: true,
					index: false,
					selection: false,
					editBtn: false,
					viewBtn: false,
					delBtn: false,
					searchBtn: false,
					refreshBtn: false,
					columnBtn: false,
					rowKey: "skuId",
					// calcHeight: 380,80,
					dialogType: "dialog",
					align: 'center',
					column: [{
						label: "规格",
						prop: "skuName",
					}, {
						label: "积分数",
						prop: "price",
					}, {
						label: "库存",
						prop: "stocks",
						type: 'number',
					}, ]
				},
				stockDetail: {},
				stockDetailOption: {
					emptyBtn: false,
					submitBtn: false,
					column: [{
						label: "规格",
						prop: "skuName",
						span:12,
						row:true,
						formslot:true,
					}, {
						label: "现有库存",
						prop: "stocks",
						span:12,
						row:true,
						formslot:true,
					}, {
						label: "调整库存",
						prop: "num",
						span:12,
						row:true,
						rules: [{
							required: true,
							message: "请输入库存",
							trigger: "blur"
						},],
					}, ]
				}
			};
		},
		components: {
			addGoods
		},
		mounted(){
			this.$EventBus.$on('finishhandle',(bool)=>{
				this.onLoad(this.page);
				this.dialogTableVisible = !bool
			})
		},
		computed: {
			...mapGetters(["permission", "userInfo"]),
			permissionList() {
				return {
					addBtn: this.vaildData(
						this.permission["/mall-cloud-base/sellerGoods/addItem"],
						false
					),
				};
			}
		},
		created() {
			getGoodsClassAll().then(res => {
				if (res.data.code == 200) {
					this.chooseProductOption = res.data.data;
				}
			});
			this.onLoad(this.page, {});
		},
		methods: {
			handleEmpty() {
				this.stockView = false
				this.$refs.stockRef.resetForm()
				this.stockDetail={}
			},
			//编辑库存提交
			handleSubmit() {
				if(this.stockDetail.num==''){
					this.$message.error( "请输入调整库存！");
					return;
				}
				if (!Number(this.stockDetail.num)) {
					this.$message.error( "调整库存量必须为数字");
					return;
				}
				let lastStocks=Number(this.stockDetail.num) +this.stockDetail.stocks
				if(lastStocks<0){
					this.$message.error( "减去的库存值不能大于现有库存!");
					return;
				}
				//防止重复提交
				if (this.goodsStockFlag) {
					this.goodsStockFlag = false;
				} else {
					return false;
				}
				let num=Number(this.stockDetail.num) 
				let type='add'
				if(num<0){
					type='subtract'
					num= -this.stockDetail.num
				}
				if(num>100000){
					this.$message.error( "调整库存不能超过100000！");
					this.goodsStockFlag=true
					return;
				}
				let data={
					isAddOrSubtract:type,
					count:num,
					skuId:this.stockDetail.skuId
				}
				editGoodsStock(data).then(res => {
					if(res.data.code==200){
						this.onStockLoad();
						this.$message({
							type: "success",
							message: "修改成功!"
						});
					}else{
						this.$message.error(res.data.message);
					}
					setTimeout(()=>{
						this.goodsStockFlag = true;
					},1000)
					this.handleEmpty()
				});
				this.onLoad(this.page);
				this.stockView = false
			},
			//编辑单条库存
			editStock(row) {
				this.stockView = true
				this.stockDetail = row
				this.stock = row.stocks
			},
			refreshStockChange() {
				this.onStockLoad();
			},
			//弹框的取消
			closeDrawer() {
				this.onLoad(this.page)
			},
			//编辑库存 打开库存列表
			editalStock(goodId) {
				this.goodId = goodId
				this.onStockLoad();
				this.stockVisible = true
			},
			onStockLoad() {
				showGoodsStock(this.goodId).then(res => {
					this.stockData = res.data.data
				})
				this.stockLoading = false;
			},
			viewGoodsDetail(id) { //编辑
				this.goodsId = id
				this.isRedact = true //编辑
				this.disadledSpec = true //编辑时候禁用选规格
				this.dialogTableVisible = true
			},
			lookOver(id) {
				//查看
				this.goodsId = id;
				this.isCheck = true;
				this.dialogTableVisible = true;
			},
			upperOrlower(id, status) {
				this.loading = true;
				upperOrlower(id, status).then(res => {
					this.loading = false;
					if (res.status == 200 && res.data.code == 200) {
						this.$message.success("操作成功！");
						//如果当前不是第一页并且最后一页剩余一条数据(解决最后一页删除完后还查询最后一页后导致空白的问题)
						if(this.page.currentPage>1 && this.page.total%this.page.pageSize==1){
							this.page.currentPage=this.page.currentPage-1;
						}
						this.onLoad(this.page, this.query);
						if (status == 0) {
							this.$emit('flush-list', 'first')
						} else {
							this.$emit('flush-list', 'second')
						}

					} else {
						this.$message.error(res.data.message);
					}

				});
			},
			searchChange(params,done) {
				this.page.currentPage=1
				this.$refs.crud.toggleSelection();
				this.query = params;
				this.onLoad(this.page, params,done);
			},
			searchReset() {
				this.query = {};
				this.$refs.crud.toggleSelection();
				this.searchForm = {};
				this.productData = [];
				this.onLoad(this.page);
			},
			// 选择项发生变化触发函数
			selectChange() {},
			currentChange(currentPage) {
				this.page.currentPage = currentPage;
				this.onLoad(this.page);
			},
			sizeChange(pageSize) {
				this.page.pageSize = pageSize;
				this.onLoad(this.page);
			},
			refreshChange() {
				this.onLoad(this.page);
			},
			onLoad(page, params = {},done) {
				params.goodsStatus = this.goodsStatus;
				if (this.productData != undefined) {
					params.goodsClassId = this.productData[2];
				}
				this.loading = true;
				getList(
					page.currentPage,
					page.pageSize,
					Object.assign(params, this.query)
				).then(res => {
					if(done){
						done();
					}
					this.loading = false;
					const data = res.data;
					this.page.total = data.count;
					if (res.status == 200) {
						this.data = data.data.map(item => {
							item["originalPrice"] = item.goodsPriceBean.originalPrice;
							item["showPrice"] = item.goodsPriceBean.showPrice;
							return item;
						});
						console.log(this.data)
					}
				});
			},
			// rowSwitchChange(row) {
			// 	if (row.storeRecommend) {
			// 		updateDisplay(row.id, "true");
			// 	} else {
			// 		updateDisplay(row.id, "false");
			// 	}
			// },
			handleChange(value) {
				console.log(value)
			}
		}
	};
</script>

<style>
	.avue-crud__menu {
		min-height: 0 !important;
		margin-bottom: 0 !important;
	}

	.fromRow[data-v-b476d630] {
		align-items: center;
	}
</style>
